import React, { PureComponent } from 'react';
import { findDOMNode } from 'react-dom';
import moment from 'moment';
import { connect } from 'dva';
import {
    List,
    Card,
    Row,
    Col,
    Radio,
    Input,
    Switch,
    Button,
    Icon,
    Dropdown,
    Menu,
    Avatar,
    Modal,
    Form,
    DatePicker,
    Select,
    Divider,
    Popconfirm,
    message
} from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Result from '@/components/Result';

import styles from './ruleList.less';
import Center from '@/pages/Account/Center/Applications';

const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const SelectOption = Select.Option;
const { Search, TextArea } = Input;

const AddRuleChild = Form.create()(props=>{
    const { form: { getFieldDecorator }, ruleVisible, okaddRule, canceladdRule, ruleItem} = props;
    const addRuleChild=()=>{
        const { form } = props
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const index = Object.keys(ruleItem).length ? ruleItem.index : null
            okaddRule(fieldsValue, index)
        });
    }
    return (
        <Modal
            title="填写参数"
            destroyOnClose
            visible={ruleVisible}
            onOk={addRuleChild}
            onCancel={canceladdRule}
        >
            <Form>
                <Form.Item
                    label="参数名"
                    labelCol={{ span: 5 }}
                    wrapperCol={{ span: 12 }}
                >
                    {getFieldDecorator('name', {
                        rules: [{ required: true, message: '请填写参数名！' }],
                        initialValue: Object.keys(ruleItem).length ? ruleItem.item.name:"" 
                    })(
                        <Input autoComplete="off" />
                    )}
                </Form.Item>
                <Form.Item
                    label="参数类型"
                    labelCol={{ span: 5 }}
                    wrapperCol={{ span: 12 }}
                >
                    {getFieldDecorator('type', {
                        rules: [{ required: true, message: '请填写参数类型！' }],
                        initialValue: Object.keys(ruleItem).length ? ruleItem.item.type:"" 
                    })(
                        <Input autoComplete="off" />
                    )}
                </Form.Item>
                <Form.Item
                    label="参数值"
                    labelCol={{ span: 5 }}
                    wrapperCol={{ span: 12 }}
                >
                    {getFieldDecorator('value', {
                        rules: [{ required: true, message: '请填写参数值！' }],
                        initialValue: Object.keys(ruleItem).length ? ruleItem.item.value : "" 
                    })(
                        <Input autoComplete="off"/>
                    )}
                </Form.Item>
            </Form>
        </Modal>
    )
})
@connect(({ loading,rule }) => ({
    rule,
    loading: loading.models.rule
}))
@Form.create()
class RuleList extends PureComponent {
    state = { visible: false, done: false,param:false, parameter: {pageSize:5}, ruleVisible: false, ruleDetail: [], ruleItem:{} };

    formLayout = {
        labelCol: { span: 7 },
        wrapperCol: { span: 13 },
    };

    componentDidMount() {
        this.showRuleList()
    }
    showRuleList =(param)=>{
        const { dispatch } = this.props;
        const { parameter} = this.state;
        if(!!param){
            parameter.page = param;
        }
        this.setState({
            parameter
        })
        dispatch({
            type: 'rule/fetchQueryRuleList',
            payload: { ...parameter },
        });
    }
    showModal = () => {
        this.setState({
            visible: true,
            ruleDetail:[],
            current: undefined,
        });
        console.log("添加规则")
    };

    showEditModal = item => {
        this.setState({
            visible: true,
            current: item,
            ruleDetail: JSON.parse(item.ruleDetail)
        });
        console.log("编辑规则",item)
    };

    handleDone = () => {
        setTimeout(() => this.addBtn.blur(), 0);
        this.setState({
            done: false,
            visible: false,
        });
    };

    handleCancel = () => {
        setTimeout(() => this.addBtn.blur(), 0);
        this.setState({
            visible: false,
        });
    };

    handleSubmit = e => {
        e.preventDefault();
        const { dispatch, form } = this.props;
        const { current, ruleDetail, parameter } = this.state;
        const id = current ? current.id : '';
        
        setTimeout(() => this.addBtn.blur(), 0);
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            if (Object.keys(ruleDetail).length){
                const data = JSON.stringify(ruleDetail)
                fieldsValue.ruleDetail = data
            }else{
                message.warning("请填写参数配置！！")
                return 
            }
            console.log(fieldsValue)
            if(id !== ''){
                fieldsValue.id = id
                dispatch({
                    type: 'rule/fetchUpdateRuleInfo',
                    payload: { ...fieldsValue },
                    callback: (res) => {
                        if(res.code !== "000000") { message.warning(res.msg); return;}
                        this.handleCancel()
                        message.success("修改成功！")
                        dispatch({
                            type: 'rule/fetchQueryRuleList',
                            payload: parameter,
                        });
                    }
                });
            }else{
                dispatch({
                    type: 'rule/fetchAddRuleInfo',
                    payload: { ...fieldsValue },
                    callback: (res) => {
                        if (res.code !== "000000") { message.warning(res.msg); return; }
                        this.handleCancel()
                        message.success("添加成功！")
                        dispatch({
                            type: 'rule/fetchQueryRuleList',
                            payload: parameter,
                        });
                    }
                });
            }
        });
    };

    deleteItem = id => {
        const { dispatch } = this.props;
        dispatch({
            type: 'list/submit',
            payload: { id },
        });
    };
    
    /**
     * 参数配置相关方法
     * okaddRule ，，canceladdRule
     * ruleChidEditer，，ruleChidDelete
     */
    handleRuleVisible=(record)=>{
        this.setState({
            ruleVisible: !!record
        })
    }
    okaddRule=(record,index)=>{
        const { ruleDetail} = this.state
        if (index !== null){
            ruleDetail.splice(index, 1,record)
        }else{
            ruleDetail.push(record)
        }
        this.setState({
            ruleDetail
        })
        this.handleRuleVisible()
    }
    canceladdRule=()=>{
        this.handleRuleVisible()
    }
    ruleChidAdd=()=>{
        this.handleRuleVisible(true)
        this.setState({
            ruleItem:{}
        })
    }
    ruleChidEditer=(item,index)=>{
        this.handleRuleVisible(true)
        this.setState({
            ruleItem:{
                item, index
            }
        })
    }
    ruleChidDelete = (index)=>{
        const { ruleDetail, param } = this.state        
        ruleDetail.splice(index, 1)
        this.setState({
            ruleDetail,
            param: !param//如果只用 ruleDetail state会莫名的不更新？不知道为什么
        });
        
    }
    handleSwitchChange = (e, record) => {
        const { dispatch } = this.props;
        const { parameter } = this.state;
        if(e){//激活
            dispatch({
                type: 'rule/fetchActiveRule',
                payload: { ruleId:record.id},
                callback: res => {
                    if (res.code !== '000000') {message.warning(res.msg);return;}
                    message.success('设置成功！！');
                    dispatch({
                        type: 'rule/fetchQueryRuleList',
                        payload: parameter,
                    });
                },
            });
        }else{//取消激活
            dispatch({
                type: 'rule/fetchUpdateRuleInfo',
                payload: record,
                callback: (res) => {
                    if (res.code !== "000000") { message.warning(res.msg); return; }                   
                    message.success("修改成功！")
                    dispatch({
                        type: 'rule/fetchQueryRuleList',
                        payload: parameter,
                    });
                }
            });
        }
        return
    };
    render() {
        const {
            rule: { ruleList },
            loading,
        } = this.props;
        const {
            form: { getFieldDecorator },
        } = this.props;
        const { visible, done, current = {}, ruleDetail, ruleVisible, ruleItem } = this.state;
        const editAndDelete = (key, currentItem) => {
            if (key === 'edit') this.showEditModal(currentItem);
            else if (key === 'delete') {
                Modal.confirm({
                    title: '删除任务',
                    content: '确定删除该任务吗？',
                    okText: '确认',
                    cancelText: '取消',
                    onOk: () => this.deleteItem(currentItem.id),
                });
            }
        };
        const modalFooter = done
            ? { footer: null, onCancel: this.handleDone }
            : { okText: '保存', onOk: this.handleSubmit, onCancel: this.handleCancel };

        const Info = ({ title, value, bordered }) => (
            <div className={styles.headerInfo}>
                <span>{title}</span>
                <p>{value}</p>
                {bordered && <em />}
            </div>
        );

        const extraContent = (
            <div className={styles.extraContent}>
                <RadioGroup defaultValue="all">
                    <RadioButton value="all">全部</RadioButton>
                    <RadioButton value="progress">进行中</RadioButton>
                    <RadioButton value="waiting">等待中</RadioButton>
                </RadioGroup>
                <Search className={styles.extraContentSearch} placeholder="请输入" onSearch={() => ({})} />
            </div>
        );  
        const ListContent = (item) => (
            <div className={styles.listContent}>
                <div className={styles.listContentItem}>
                    <span>车辆类型</span>
                    <p>{item.data.vehicleType}</p>
                </div>
                <div className={styles.listContentItem}>
                    <span>开始时间</span>
                    <p>{item.data.createTime}</p>
                    {/* <p>{moment(createdAt).format('YYYY-MM-DD HH:mm')}</p> */}
                </div>
                <div className={styles.listContentItem}>
                    {/* <Progress percent={percent} status={status} strokeWidth={6} style={{ width: 180 }} /> */}
                    <Switch            
                        checked={item.data.isActive ? true : false}
                        // loading={loading}
                        // style={{ position: 'relative', top: '-2px' }}
                        onChange={e => this.handleSwitchChange(e, item.data)}
                    />
                </div>
            </div>
        );

        const MoreBtn = props => (
            <Dropdown
                overlay={
                    <Menu onClick={({ key }) => editAndDelete(key, props.current)}>
                        <Menu.Item key="edit">编辑</Menu.Item>
                        <Menu.Item key="delete">删除</Menu.Item>
                    </Menu>
                }
            >
                <a>
                    更多 <Icon type="down" />
                </a>
            </Dropdown>
        );
/**
 * 新增-编辑=》dom
 */
        const ChildRule = (props)=>{
            const { ruleDetail} = props
            return(
                <div style={{ textAlign: "center" }}>
                    <section>
                        {
                            ruleDetail.map((item, index) => {
                                return (
                                    <div className="ant-row ant-form-item" key={index}>
                                        <div className="ant-col-7 ant-form-item-label">
                                            <label>{item.name}</label>
                                        </div>
                                        <div className="ant-col-8 ant-form-item-control-wrapper">
                                            <div className="ant-form-item-control">
                                                <span className="ant-form-item-children">
                                                    <Input disabled value={item.value}></Input>
                                                </span>
                                            </div>
                                        </div>
                                        <div className="ant-col-5 ant-form-item-label">
                                            <label>
                                                <Button size="small" onClick={() => this.ruleChidEditer(item, index)}>编辑</Button>
                                                &nbsp;&nbsp;
                                                <Popconfirm
                                                    title="确定删除该选项么?"
                                                    onConfirm={() => this.ruleChidDelete(index)}
                                                    onCancel={() => { }}
                                                    okText="Yes"
                                                    cancelText="No"
                                                >
                                                    <Button size="small" type="danger">
                                                        删除
                                                    </Button>
                                                </Popconfirm>
                                            </label>
                                        </div>
                                    </div>
                                )
                            })
                        }

                    </section>
                    <p>
                        <Button type="dashed" style={{ width: '40%' }} onClick={() => this.ruleChidAdd()}>
                            <Icon type="plus" /> 添加
                        </Button>
                    </p>
                </div>
            )
        }
        const getModalContent = () => {
            return (
                <Form>
                    <FormItem label="规则名称" {...this.formLayout}>
                        {getFieldDecorator('ruleName', {
                            rules: [{ required: true, message: '请输入规则名称' }],
                            initialValue: current.ruleName,
                        })(<Input placeholder="请输入"  autoComplete="off" />)}
                    </FormItem>
                    <FormItem label="规则类型" {...this.formLayout}>
                        {getFieldDecorator('ruleType', {
                            rules: [{ required: true, message: '请输入规则类型' }],
                            initialValue: current.ruleType,
                        })(
                            <Input placeholder="请输入" autoComplete="off" />
                        )}
                    </FormItem>
                    <FormItem label="车辆类型" {...this.formLayout}>
                        {getFieldDecorator('vehicleType', {
                            rules: [{ required: true, message: '请选择车辆类型' }],
                            initialValue: current.vehicleType,
                        })(
                            <Select placeholder="请选择">
                                <SelectOption key={1}>重卡</SelectOption>
                                <SelectOption key={2}>新能源</SelectOption>
                            </Select>
                        )}
                    </FormItem>
                    <FormItem label="规则版本" {...this.formLayout}>
                        {getFieldDecorator('version', {
                            rules: [{ required: true, message: '请输入规则版本' }],
                            initialValue: current.version,
                        })(
                            <Input placeholder="请输入" autoComplete="off" />
                        )}
                    </FormItem>
                    <FormItem label="开始时间" {...this.formLayout}>
                        {getFieldDecorator('createTime', {
                            rules: [{ required: true, message: '请选择开始时间' }],
                            // initialValue: current.createTime || null,
                        })(
                            <DatePicker
                                showTime
                                placeholder="请选择"
                                format="YYYY-MM-DD HH:mm:ss"
                                style={{ width: '100%' }}
                            />
                        )}
                    </FormItem>
                    <FormItem {...this.formLayout} label="规则描述">
                        {getFieldDecorator('remark', {
                            rules: [{ required: true,message: '请输入至少五个字符的规则描述！', min: 5 }],
                            initialValue: current.remark,
                        })(<TextArea rows={4} placeholder="请输入至少五个字符" />)}
                    </FormItem>
                    <Divider orientation="left" style={{ paddingLeft: 30,paddingRight:30 }}><span style={{fontSize:13}}>参数配置</span></Divider>
                    <ChildRule ruleDetail={ruleDetail} ></ChildRule>
                    
                </Form>
            );
        };
        const addRuleFn = {
            okaddRule: this.okaddRule,
            canceladdRule: this.canceladdRule
        }
        return (
            <PageHeaderWrapper>
                <div className={styles.standardList}>
                    <Card bordered={false}>
                        <Row>
                            <Col sm={8} xs={24}>
                                <Info title="我的待办" value="8个任务" bordered />
                            </Col>
                            <Col sm={8} xs={24}>
                                <Info title="本周任务平均处理时间" value="32分钟" bordered />
                            </Col>
                            <Col sm={8} xs={24}>
                                <Info title="本周完成任务数" value="24个任务" />
                            </Col>
                        </Row>
                    </Card>

                    <Card
                        className={styles.listCard}
                        bordered={false}
                        title="规则列表"
                        style={{ marginTop: 24 }}
                        bodyStyle={{ padding: '0 32px 40px 32px' }}
                        extra={extraContent}
                    >
                        <Button
                            type="dashed"
                            style={{ width: '100%', marginBottom: 8 }}
                            icon="plus"
                            onClick={this.showModal}
                            ref={component => {
                                /* eslint-disable */
                                this.addBtn = findDOMNode(component);
                                /* eslint-enable */
                            }}
                        >
                            添加
                        </Button>
                        <List
                            size="large"
                            rowKey="id"
                            loading={loading}
                            dataSource={ruleList.list}
                            pagination={{
                                ...ruleList.pagination,
                                onChange: (page) => {                                    
                                    this.showRuleList(page)
                                },
                            }}
                            renderItem={item => (
                                <List.Item
                                    actions={[
                                        <a
                                            onClick={e => {
                                                e.preventDefault();
                                                this.showEditModal(item);
                                            }}
                                        >
                                            编辑
                                        </a>,
                                        <MoreBtn current={item} />,
                                    ]}
                                >
                                    <List.Item.Meta
                                        avatar={<Avatar src="https://gw.alipayobjects.com/zos/rmsportal/dURIMkkrRFpPgTuzkwnB.png" shape="square" size="large" />}
                                        title={<span>{item.ruleName}</span>}
                                        description={item.remark}
                                    />
                                    <ListContent data={item} />
                                </List.Item>
                            )}
                        />
                    </Card>
                </div>
                <Modal
                    title={done ? null : `规则${Object.keys(current).length ? '编辑' : '添加'}`}
                    className={styles.standardListForm}
                    width={640}
                    bodyStyle={done ? { padding: '72px 0' } : { padding: '28px 0 0' }}
                    destroyOnClose
                    visible={visible}
                    {...modalFooter}
                >
                    {getModalContent()}
                </Modal>
                
                <AddRuleChild ruleVisible={ruleVisible} {...addRuleFn} ruleItem={ruleItem}/>
            </PageHeaderWrapper>
        );
    }
}

export default RuleList;
